//
//  MXSOAuthVC.swift
//  weibo
//
//  Created by 孙飞 on 15/12/8.
//  Copyright © 2015年 Sunfei. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking



let WB_APPKEY = "3671038985"
let WB_APP_SECRET = "4c84a91734c8017a4c7203ed6610a3f4"
let WB_REDIRECT_URI = "http://open.weibo.com/"


class MXSOAuthVC: UIViewController ,UIWebViewDelegate{

    
    private lazy var webView = UIWebView()
    
    override func loadView() {
        webView.delegate = self
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
//        view.backgroundColor = UIColor.orangeColor()
        setupUI()
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_APPKEY)&redirect_uri=\(WB_REDIRECT_URI)"
        
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        
        webView.loadRequest(request)
        
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
//        if let url = request.URL?.absoluteString{
//            return true
//        }
//        
//        print(request.URL)
//        print(request.URL!.absoluteString)
//        print(request.URL!.query)
        
        guard let url = request.URL?.absoluteString else{
            return true
        }
        if !url.hasPrefix(WB_REDIRECT_URI){
            return true
        }
        
        if request.URL!.query!.hasPrefix("code="){
            
            let code = request.URL!.query!.substringFromIndex("code=".endIndex)
            
//            let urlString = "https://api.weibo.com/oauth2/access_token"
//            // 请求参数
//            let params = [
//                "client_id": WB_APPKEY,
//                "client_secret": WB_APP_SECRET,
//                "grant_type": "authorization_code",
//                "code": code,
//                "redirect_uri": WB_REDIRECT_URI
//            ]
            
//            let maneger: AFHTTPSessionManager?
//            maneger!.GET(urlString, parameters: params, success: { (_, response) -> Void in
//
//                }, failure: { (_, error) -> Void in
//                    print("qingqiushibai")
//                    
//            })
            
            MXSUserAccountVM.sharedAccount.loadAccessToken(code, complete: { (isSuccessed) -> () in
                if !isSuccessed {
                    print("加载失败")
                    SVProgressHUD.showErrorWithStatus("网络异常,登录失败")
                    return
                }
                print("登录成功")
                
                SVProgressHUD.dismiss()
                
// *********** 使用present方法弹出的控制器 才能使用 dismiss方法销毁当前控制器
                
                self.dismissViewControllerAnimated(true, completion: nil)
//                let welcome = MXSWelcomeVC()
//                self.navigationController?.pushViewController(welcome, animated: true)
                // 2.跳到欢迎页
                // 切换根控制器的逻辑,应该放在一起,一般放在 appdelegate 里面
                NSNotificationCenter.defaultCenter().postNotificationName(MXSSwitchRootVCNotifation, object: self)
                
            })
            
        }else{
//            print(request.URL)
            dismiss()
        }
        
        return false
    }
    
    
    func setupUI(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "dismiss")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "autoFill")
        navigationItem.title = "微博登录"
    }
    
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    
    
    
    // MARK: - 左右导航按钮
    @objc private func dismiss(){
        
        SVProgressHUD.dismiss()
        print("dismiss")
        dismissViewControllerAnimated(true, completion: nil)
        
//        navigationController?.popViewControllerAnimated(true)
    }
    
    
    @objc private func autoFill(){
        
        let jsString = "document.getElementById('userId').value='michauxs@sina.com';document.getElementById('passwd').value='laopo930312'"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    

}
